package org.testis.utils.middleware;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import org.orm.PersistentException;
import org.orm.PersistentTransaction;
import org.testis.orm.classes.*;
import org.testis.orm.manager.TestisDbPersistentManager;
import org.testis.orm.refinedclasses.*;
import org.testis.orm.refinedclasses.TestDesignTreeRefined.TestDesignTreeParameters;
import org.testis.utils.parametermodel.ParameterModel;
import org.testis.utils.parametermodel.ParameterTable;

/**
 * 
 * @author Cahit Emir Erel
 */
public class TestDesign {

    private static TestDesign m_reference;
    private static HashMap<String, T_test_designparttype> m_designTypes = new HashMap<String, T_test_designparttype>();
    public static HashMap<String, T_test_owners> m_owners = new HashMap<String, T_test_owners>();
    public static HashMap<String, T_test_actions> m_actions = new HashMap<String, T_test_actions>();
    public static HashMap<String, T_test_modultype> m_modulTypes = new HashMap<String, T_test_modultype>();
    public static HashMap<String, T_test_dataobject_result_types> m_dataObjectResultTypes = new HashMap<String, T_test_dataobject_result_types>();
    public static HashMap<String, T_test_stepcontainer> m_testSuites = new HashMap<String, T_test_stepcontainer>();
    public static HashMap<String, T_test_devicegroup> m_deviceGroups = new HashMap<String, T_test_devicegroup>();

    public static final TestDesign newInstance() {
	if (m_reference == null) {
	    m_reference = new TestDesign();
	}
	return m_reference;
    }

    private TestDesign() {
	int i;
	int j;
	int k;
	T_test_designparttype[] typeList = getTestDesignPartTypes();
	for (i = 0; i < typeList.length; i++) {
	    m_designTypes.put(typeList[i].getName(), typeList[i]);
	}
	T_test_stepcontainerCriteria containerCriteria;
	try {
	    containerCriteria = new T_test_stepcontainerCriteria();
	    containerCriteria.containerTypeId.eq(TestDesign
		    .getDesignPartTypeIdByName("TestSuite"));
	    T_test_stepcontainer[] testSuiteList = containerCriteria
		    .listT_test_stepcontainer();
	    for (i = 0; i < testSuiteList.length; i++) {
		m_testSuites.put(testSuiteList[i].getName(), testSuiteList[i]);
	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}

	T_test_owners[] ownerList = getOwners();
	for (i = 0; i < ownerList.length; i++) {
	    m_owners.put(ownerList[i].getTagName(), ownerList[i]);
	}

	T_test_modultype[] modulTypeList = getModuleTypeList();
	T_test_actions[] actionList;
	for (i = 0; i < modulTypeList.length; i++) {
	    m_modulTypes.put(modulTypeList[i].getName(), modulTypeList[i]);
	    actionList = getActionsByModulType(modulTypeList[i].getName());
	    for (j = 0; j < actionList.length; j++) {
		m_actions.put(actionList[j].getName(), actionList[j]);

	    }
	}
	T_test_dataobject_result_types[] resultTypes = getExpectedResultTypes();
	for (i = 0; i < resultTypes.length; i++) {
	    m_dataObjectResultTypes.put(resultTypes[i].getName(),
		    resultTypes[i]);
	}

	T_test_devicegroup[] deviceGroupList = getSupportedDevices();
	for (i = 0; i < deviceGroupList.length; i++) {
	    m_deviceGroups
		    .put(deviceGroupList[i].getName(), deviceGroupList[i]);
	}

    }

    public static String getExpectedResultTypeName(Integer id) {
	T_test_dataobject_result_types[] types = getExpectedResultTypes();
	for (int i = 0; i < types.length; i++) {
	    if (types[i].getId() == id) {
		return types[i].getName();
	    }
	}
	return null;
    }

    public static T_test_dataobject_result_types getExpectedResultTypeById(
	    Integer id) {
	T_test_dataobject_result_types[] types = getExpectedResultTypes();
	for (int i = 0; i < types.length; i++) {
	    if (types[i].getId() == id) {
		return types[i];
	    }
	}
	return null;
    }

    private T_test_label[] getLabels() {
	LabelDataHandler handler = new LabelDataHandler();
	return handler.getLabelsAsArray();
    }

    public boolean checkTestSuiteNameUniqueness(String name) {
	if (m_testSuites.containsKey(name)) {
	    return false;
	} else {
	    return true;
	}
    }

    public String getTestPcMacAddress(Integer testBedId, String testPcName) {
	T_bed_devicegroup_detailsCriteria criteria;
	try {
	    criteria = new T_bed_devicegroup_detailsCriteria();
	    criteria.createGroupCriteria().id.eq(testBedId);
	    criteria.createPcCriteria().name.eq(testPcName);

	    T_bed_devicegroup_details details = criteria
		    .uniqueT_bed_devicegroup_details();
	    if (details != null) {
		return details.getMacAddress();
	    }
	    return null;
	} catch (PersistentException ex) {
	}
	return null;
    }

    public LinkedList<String> getTestPcMacAddressess(Integer testBedId) {
	T_bed_devicegroup_detailsCriteria criteria;
	LinkedList<String> output = new LinkedList<String>();
	try {
	    criteria = new T_bed_devicegroup_detailsCriteria();
	    criteria.createGroupCriteria().id.eq(testBedId);
	    T_bed_devicegroup_details[] details = criteria
		    .listT_bed_devicegroup_details();
	    if (details != null) {
		for (int i = 0; i < details.length; i++) {
		    output.add(details[i].getMacAddress());
		}

	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return output;
    }

    public static T_bed_networkadapters getNicByName(String name, String pcName) {
	T_bed_networkadaptersCriteria criteria;
	try {
	    criteria = new T_bed_networkadaptersCriteria();
	    criteria.name.eq(name);
	    criteria.createPcCriteria().name.eq(pcName);
	    return criteria.uniqueT_bed_networkadapters();
	} catch (PersistentException ex) {
	}
	return null;
    }

    public static T_bed_networkadapters getNicById(Integer id) {
	T_bed_networkadaptersCriteria criteria;
	try {
	    criteria = new T_bed_networkadaptersCriteria();
	    criteria.id.eq(id);
	    return criteria.uniqueT_bed_networkadapters();
	} catch (PersistentException ex) {
	}
	return null;
    }

    public String[] getNicNamesByPcName(String pcName) {
	String[] results = null;
	T_bed_testpcCriteria criteria;
	try {
	    criteria = new T_bed_testpcCriteria();
	    criteria.name.eq(pcName);
	    T_bed_testpc pc = criteria.uniqueT_bed_testpc();
	    T_bed_networkadapters[] nicList = pc.t_bed_networkadapters
		    .toArray();

	    results = new String[nicList.length];
	    for (int i = 0; i < nicList.length; i++) {
		results[i] = nicList[i].getName();
	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return results;
    }

    public HashMap getTestBedList() {
	HashMap testBeds = new HashMap();
	T_bed_devicegroup[] groups;
	try {
	    groups = T_bed_devicegroupFactory.listT_bed_devicegroupByQuery(
		    null, null);
	    for (int i = 0; i < groups.length; i++) {
		testBeds.put(groups[i].getId(), groups[i].getName());
	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return HashMapUtils.sortHashMapByValues(testBeds);
    }

    public TestDesignTreeNode getTestDesignTreeByName(boolean showOutput,
	    String name) {
	return getTestDesignTreeData(showOutput, name);
    }

    private void constructFlyweightTree(TestDesignTreeNode parent,
	    T_test_designtree traverseNode,
	    HashMap<Integer, TestDesignTreeNode> hashMap)
	    throws PersistentException {
	TestDesignTreeNode temp;
	T_test_designtree[] children = null;
	HashMap<Integer, T_test_designtree> hmap;
	LinkedList<TestDesignTreeNode> childrenLinkedList = new LinkedList<TestDesignTreeNode>();

	if (parent != null) {
	    if (parent.getReference() != null) {
		if (parent.getReference().getTreeReference() != null) {
		    children = parent.getReference().getTreeReference().t_test_designtree
			    .toArray();
		}
	    }
	}
	if (children == null) {
	    children = new T_test_designtree[] { traverseNode };
	}
	if (children != null && children.length > 0) {
	    hmap = new HashMap(children.length);
	    T_test_designtree eldestSibling = null;
	    int id;
	    Integer nextRankId;
	    for (int i = 0; i < children.length; i++) {

		nextRankId = children[i].getRank();
		if (nextRankId != null) {
		    id = nextRankId.intValue();
		} else {
		    id = -1;
		}
		hmap.put(id, children[i]);
	    }
	    eldestSibling = hmap.remove(-1);
	    if (eldestSibling == null) {
		if (parent == null || parent.getReference() == null
			|| parent.getReference().getTreeReference() == null) {
		    throw new PersistentException(
			    "SILENT FAILURE! RANKING ERROR FOR BROKEN TREE PART");
		} else {
		    throw new PersistentException(
			    "RANKING ERROR: FIRST CHILD SHOULD HAVE NULL RANK ! Check nodes with Parent Id: "
				    + parent.getId());
		}
	    }
	    do {
		temp = hashMap.get(eldestSibling.getId());
		boolean nodeExists = true;
		if (temp == null) {
		    nodeExists = false;
		    TestDesignTreeRefined eldest = TestDesignTreeRefined
			    .getDesignTree(eldestSibling);
		    temp = TestDesignTreeNode.getNode(eldest);
		    hashMap.put(eldestSibling.getId(), temp);
		}
		if (traverseNode != null
			&& eldestSibling.getId() == traverseNode.getId()) {
		    constructFlyweightTree(temp, null, hashMap);
		}
		if (!nodeExists && parent != null) {
		    parent.addChild(temp);
		}
		childrenLinkedList.add(temp);
		eldestSibling = hmap.remove(eldestSibling.getId());
	    } while (eldestSibling != null);

	    // THROUBLESHOOTING MESSAGE
	    if (children.length != childrenLinkedList.size()) {
		Integer treeId;
		Integer parentId;
		LinkedList<Integer> treeIds = new LinkedList<Integer>();
		LinkedList<Integer> parentIds = new LinkedList<Integer>();
		boolean add;
		for (int i = 0; i < childrenLinkedList.size(); i++) {
		    add = true;
		    treeId = childrenLinkedList.get(i).getId();
		    parentId = childrenLinkedList.get(i).getParent().getId();
		    for (int j = 0; j < parentIds.size(); j++) {
			if (parentIds.get(j) == parentId.intValue()) {
			    add = false;
			    break;
			}
		    }
		    if (add) {
			parentIds.add(parentId);
			treeIds.add(treeId);
		    }
		}
		StringBuffer buffer = new StringBuffer();

		buffer.append("WRONG NO OF CHILDREN ERROR: LINKED LIST RANK ERROR DETECTED!");
		buffer.append("\nCheck nodes with Parent Id");
		for (int i = 0; i < parentIds.size(); i++) {
		    buffer.append(" : " + parentIds.get(i));
		}
		if (parentIds.size() > 1) {
		    buffer.append("\nAlso Check nodes with Id");
		    for (int i = 0; i < treeIds.size(); i++) {
			buffer.append(" : " + treeIds.get(i));
		    }
		}
		System.out.println(buffer.toString());
		throw new PersistentException(buffer.toString());
	    }
	}
    }

    public TestDesignTreeNode getFlyWeightTestDesignTree(LinkedList list) {
	try {
	    // System.out.println("-- GET FLYWEIGHT TEST DESIGN TREE --");
	    TestDesignTreeNode tempRoot = TestDesignTreeNode.createEmptyNode();
	    TestDesignTreeNode root = null;
	    TestDesignTreeNode result = null;
	    TestDesignTreeNode parent = null;
	    TestDesignTreeNode tempResult = null;
	    T_test_designtree temp = null;
	    boolean tempRootInUse;
	    LinkedList<T_test_designtree> depthSortedNodeList = new LinkedList<T_test_designtree>();
	    LinkedList<Integer> depthSortedNumberList = new LinkedList<Integer>();
	    HashMap<Integer, TestDesignTreeNode> hashMap = new HashMap<Integer, TestDesignTreeNode>();
	    int depth;
	    int addPoint;
	    // System.out.println("NUMBER OF NODES IN THE TREE: " +
	    // list.size());
	    for (int i = 0; i < list.size(); i++) {
		depth = 0;
		addPoint = 0;
		temp = (T_test_designtree) list.get(i);
		while (temp.getParent() != null) {
		    depth++;
		    temp = temp.getParent();
		}
		for (int j = 0; j < depthSortedNumberList.size(); j++) {
		    if (depth <= depthSortedNumberList.get(j)) {
			addPoint = j;
			break;
		    }
		}
		if (depthSortedNumberList.size() == addPoint) {
		    depthSortedNumberList.add(depth);
		    depthSortedNodeList.add((T_test_designtree) list.get(i));
		} else {
		    depthSortedNumberList.add(addPoint, depth);
		    depthSortedNodeList.add(addPoint,
			    (T_test_designtree) list.get(i));
		}
	    }
	    for (int i = 0; i < depthSortedNodeList.size(); i++) {
		tempRootInUse = false;
		temp = depthSortedNodeList.get(i);
		T_test_designtree tempParent = temp.getParent();
		if (tempParent != null) {
		    if (!hashMap.containsKey(tempParent.getId())) {
			TestDesignTreeRefined tempParentNode = TestDesignTreeRefined
				.getDesignTree(tempParent);
			hashMap.put(tempParent.getId(),
				TestDesignTreeNode.getNode(tempParentNode));
		    }
		    parent = hashMap.get(tempParent.getId());
		} else {
		    parent = tempRoot;
		    tempRootInUse = true;
		}

		constructFlyweightTree(parent, temp, hashMap);
		result = parent;
		/*
		 * if (result == null || (result != null && result.getParent()
		 * != null)) { continue; }
		 */
		temp = temp.getParent();
		if (temp != null) {
		    while (temp.getParent() != null) {
			temp = temp.getParent();
			tempResult = hashMap.get(temp.getId());
			if (tempResult == null) {
			    TestDesignTreeRefined tempNode = TestDesignTreeRefined
				    .getDesignTree(temp);
			    tempResult = TestDesignTreeNode.getNode(tempNode);
			    hashMap.put(temp.getId(), tempResult);
			    if (result.getParent() == null) {
				tempResult.addChild(result);
			    }
			} else {
			    tempResult.addChild(result);
			    break;
			}
			result = tempResult;
		    }
		}
		if (root == null) {
		    if (tempRootInUse) {
			root = tempRoot.getChildren()[0];
		    } else {
			root = result;
		    }
		}
	    }
	    return root;
	} catch (PersistentException ex) {
	    System.out.println(ex.getLocalizedMessage() + "\n");
	    return null;
	}
    }

    public void closeDBConnection() throws PersistentException {
	TestisDbPersistentManager.instance().disposePersistentManager();
    }

    public String[] getKeys(T_test_teststeps step) {
	String[] result = null;
	T_test_module_action_paramtersCriteria criteria;
	T_test_module_action_paramters[] params = null;
	try {
	    criteria = new T_test_module_action_paramtersCriteria();
	    criteria.createActionCriteria().id.eq(step.getActionId());
	    params = criteria.listT_test_module_action_paramters();
	} catch (PersistentException ex) {
	}
	if (params != null) {
	    result = new String[params.length];
	    for (int i = 0; i < params.length; i++) {
		result[i] = params[i].getParameter().getName();
	    }
	} else {
	    result = new String[0];
	}
	return result;
    }

    public String[] getExpectedResultTypesList() {
	String[] result = null;
	T_test_dataobject_result_types[] types = getExpectedResultTypes();
	result = new String[types.length];
	for (int i = 0; i < types.length; i++) {
	    result[i] = types[i].getName();
	}
	return result;
    }

    private static T_test_dataobject_result_types[] getExpectedResultTypes() {
	try {
	    return T_test_dataobject_result_typesFactory
		    .listT_test_dataobject_result_typesByQuery(null, null);
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return null;
    }

    private T_test_designparttype[] getTestDesignPartTypes() {
	try {
	    return T_test_designparttypeFactory
		    .listT_test_designparttypeByQuery(null, null);
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return null;
    }

    public String[] getDutNamesByPcName(String pcName) {
	String[] results = null;
	T_bed_testpcCriteria criteria;
	try {
	    criteria = new T_bed_testpcCriteria();
	    criteria.name.eq(pcName);
	    T_bed_testpc pc = criteria.uniqueT_bed_testpc();
	    T_bed_dut[] dutList = pc.t_bed_dut.toArray();
	    results = new String[dutList.length];
	    for (int i = 0; i < dutList.length; i++) {
		results[i] = dutList[i].getName();
	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}

	return results;
    }

    public T_bed_dut[] getDutList() {
	try {
	    return T_bed_dutFactory.listT_bed_dutByQuery(null, null);
	} catch (PersistentException ex) {
	}
	return null;
    }

    public static T_bed_dut getDutById(String key) {
	T_bed_dutCriteria dutList;
	try {
	    dutList = new T_bed_dutCriteria();
	    dutList.name.eq(key);
	    return dutList.uniqueT_bed_dut();
	} catch (PersistentException ex) {
	}
	return null;
    }

    public static T_bed_dut getDutById(Integer id) {
	T_bed_dutCriteria dutList;
	try {
	    dutList = new T_bed_dutCriteria();
	    dutList.id.eq(id);
	    return dutList.uniqueT_bed_dut();
	} catch (PersistentException ex) {
	}
	return null;
    }

    public T_test_actions[] getActionsByModulType(String modulTypeName) {
	T_test_actionlist[] actionlist = m_modulTypes.get(modulTypeName).t_test_actionlist
		.toArray();
	T_test_actions[] results = new T_test_actions[actionlist.length];
	for (int i = 0; i < actionlist.length; i++) {
	    results[i] = actionlist[i].getAction();
	}
	return results;
    }

    public String[] getActionNamesByModulType(String modulTypeName) {
	T_test_actionlist[] actionlist = m_modulTypes.get(modulTypeName).t_test_actionlist
		.toArray();
	String[] results = new String[actionlist.length];
	for (int i = 0; i < actionlist.length; i++) {
	    results[i] = actionlist[i].getAction().getName();
	}
	return results;
    }

    public static Integer getActionTypeIdByName(String name) {
	T_test_actions actionType = m_actions.get(name);
	if (actionType != null) {
	    return actionType.getId();
	}
	return null;
    }

    public static String getActionTypeName(Integer id) {
	if (id == null) {
	    return null;
	}
	T_test_actions actionType = getActionTypeById(id);
	if (actionType != null) {
	    return actionType.getName();
	}
	return null;
    }

    public static T_test_actions getActionTypeById(Integer id) {
	if (id == null) {
	    return null;
	}
	T_test_actions actionType = null;
	Iterator<T_test_actions> iter = m_actions.values().iterator();
	while (iter.hasNext()) {

	    T_test_actions temp = iter.next();
	    if (temp.getId() == id) {
		actionType = temp;
		break;

	    }
	}
	return actionType;
    }

    public static Integer getSupportedDeviceGroupIdByName(String name) {
	T_test_devicegroup deviceGroup = m_deviceGroups.get(name);
	if (deviceGroup != null) {
	    return deviceGroup.getId();
	}
	return null;
    }

    public static String getSupportedDeviceGroupName(Integer id) {
	if (id == null) {
	    return null;
	}
	T_test_devicegroup deviceGroup = getSupportedDeviceGroupById(id);
	if (deviceGroup != null) {
	    return deviceGroup.getName();
	}
	return null;
    }

    public static T_test_devicegroup getSupportedDeviceGroupById(Integer id) {
	if (id == null) {
	    return null;
	}
	T_test_devicegroup deviceGroup = null;
	Iterator<T_test_devicegroup> iter = m_deviceGroups.values().iterator();
	while (iter.hasNext()) {

	    T_test_devicegroup temp = iter.next();
	    if (temp.getId() == id) {
		deviceGroup = temp;
		break;

	    }
	}
	return deviceGroup;
    }

    public static Integer getModuleTypeIdByName(String name) {

	T_test_modultype moduleType = m_modulTypes.get(name);
	if (moduleType != null) {
	    return moduleType.getId();
	}
	return null;
    }

    public static String getModuleTypeName(Integer id) {
	if (id == null) {
	    return null;
	}
	T_test_modultype moduleType = getModuleTypeById(id);
	if (moduleType != null) {
	    return moduleType.getName();
	}
	return null;
    }

    public static T_test_modultype getModuleTypeById(Integer id) {
	if (id == null) {
	    return null;
	}
	T_test_modultype moduleType = null;
	Iterator<T_test_modultype> iter = m_modulTypes.values().iterator();
	while (iter.hasNext()) {

	    T_test_modultype temp = iter.next();
	    if (temp.getId() == id) {
		moduleType = temp;
		break;

	    }
	}
	return moduleType;
    }

    public T_test_modultype[] getModuleTypeList() {
	T_test_modultype[] moduls = null;
	if (m_modulTypes.size() == 0) {
	    try {
		moduls = T_test_modultypeFactory.listT_test_modultypeByQuery(
			null, null);
	    } catch (PersistentException ex) {
		ex.printStackTrace();
	    }
	} else {
	    moduls = m_modulTypes.values().toArray(
		    new T_test_modultype[m_modulTypes.size()]);
	}
	return moduls;
    }

    public String[] getModuleTypeListNames() {
	return m_modulTypes.keySet().toArray(new String[m_modulTypes.size()]);
    }

    private T_bed_testpc[] getPcList() {

	try {
	    return T_bed_testpcFactory.listT_bed_testpcByQuery(null, null);
	} catch (PersistentException ex) {
	}

	return null;
    }

    public String[] getPcNames() {
	String[] pcList = null;
	T_bed_testpc[] pcs;
	try {
	    pcs = T_bed_testpcFactory.listT_bed_testpcByQuery(null, null);
	    if (pcs != null) {
		pcList = new String[pcs.length];
	    }
	    for (int i = 0; i < pcs.length; i++) {
		pcList[i] = pcs[i].getName();
	    }
	} catch (PersistentException ex) {
	}

	return pcList;
    }

    public static T_bed_testpc getPcByName(String name) {
	T_bed_testpc pc = null;
	try {
	    T_bed_testpcCriteria criteria = new T_bed_testpcCriteria();
	    criteria.name.eq(name);
	    pc = criteria.uniqueT_bed_testpc();
	} catch (PersistentException ex) {
	}

	return pc;
    }

    public static T_bed_testpc getPcById(Integer id) {
	T_bed_testpc pc = null;
	try {
	    T_bed_testpcCriteria criteria = new T_bed_testpcCriteria();
	    criteria.id.eq(id);
	    pc = criteria.uniqueT_bed_testpc();
	} catch (PersistentException ex) {
	}

	return pc;
    }

    public String[] getDeviceGroupPcNames() {
	String[] groupPcs = null;
	T_bed_devicegroup_details[] groupPcsDetails;
	try {
	    groupPcsDetails = T_bed_devicegroup_detailsFactory
		    .listT_bed_devicegroup_detailsByQuery(null, null);
	    if (groupPcsDetails != null) {
		groupPcs = new String[groupPcsDetails.length];
	    }
	    for (int i = 0; i < groupPcsDetails.length; i++) {
		groupPcs[i] = groupPcsDetails[i].getName();
	    }
	} catch (PersistentException ex) {
	}
	return groupPcs;
    }

    private T_test_designparttype getDesignPartTypeByName(String name) {
	return m_designTypes.get(name);
    }

    public static int getDesignPartTypeIdByName(String name) {
	T_test_designparttype part = m_designTypes.get(name);
	if (part != null) {
	    return part.getId();
	}
	return 0;
    }

    public static String getDesignPartTypeName(int id) {
	T_test_designparttype partType = getDesignPartTypeById(id);
	if (partType != null) {
	    return partType.getName();
	}
	return null;
    }

    public static T_test_designparttype getDesignPartTypeById(int id) {
	T_test_designparttype partType = null;
	Iterator<T_test_designparttype> iter = m_designTypes.values()
		.iterator();
	while (iter.hasNext()) {

	    T_test_designparttype temp = iter.next();
	    if (temp.getId() == id) {
		partType = temp;
		break;

	    }
	}
	return partType;
    }

    public static T_test_designparttype[] getDesignPartTypes() {
	try {

	    return T_test_designparttypeFactory
		    .listT_test_designparttypeByQuery(null, null);
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return null;
    }

    private T_test_devicegroup[] getSupportedDevices() {
	try {
	    return T_test_devicegroupFactory.listT_test_devicegroupByQuery(
		    null, null);
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return null;
    }

    public String[] getSupportedDeviceNames() {
	return m_deviceGroups.keySet().toArray(
		new String[m_deviceGroups.size()]);
    }

    private T_test_owners[] getOwners() {
	try {
	    return T_test_ownersFactory.listT_test_ownersByQuery(null, null);
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return null;
    }

    public TestDesignTreeNode contructPartialDesignTree(
	    TestDesignTreeRefined node) {
	TestDesignTreeNode root = null;
	try {
	    constructDesignTree(node, root);
	    return root.getChildren()[0];
	} catch (PersistentException ex) {
	    return null;
	}
    }

    private TestDesignTreeNode constructDesignTree(TestDesignTreeRefined node,
	    TestDesignTreeNode parent) throws PersistentException {

	TestDesignTreeNode thisNode = TestDesignTreeNode.getNode(node);
	if (parent != null) {
	    parent.addChild(thisNode);
	}
	LinkedList<T_test_designtree> childrenLinkedList = new LinkedList<T_test_designtree>();
	T_test_designtree[] children = node.getTreeReference().t_test_designtree
		.toArray();
	HashMap<Integer, T_test_designtree> hmap;
	if (children != null && children.length > 0) {
	    hmap = new HashMap(children.length);
	    T_test_designtree eldestSibling = null;
	    int id;
	    Integer nextRankId;
	    for (int i = 0; i < children.length; i++) {

		nextRankId = children[i].getRank();
		if (nextRankId != null) {
		    id = nextRankId.intValue();
		} else {
		    id = -1;
		}
		hmap.put(id, children[i]);
	    }
	    eldestSibling = hmap.remove(-1);
	    if (eldestSibling == null) {
		throw new PersistentException(
			"RANKING ERROR: FIRST CHILD SHOULD HAVE NULL RANK ! Check nodes with Parent Id: "
				+ node.getId());
	    }
	    do {
		childrenLinkedList.add(eldestSibling);
		eldestSibling = hmap.remove(eldestSibling.getId());
	    } while (eldestSibling != null);
	    if (children.length != childrenLinkedList.size()) {
		Integer treeId;
		Integer parentId;
		LinkedList<Integer> treeIds = new LinkedList<Integer>();
		LinkedList<Integer> parentIds = new LinkedList<Integer>();
		boolean add;
		for (int i = 0; i < childrenLinkedList.size(); i++) {
		    add = true;
		    treeId = childrenLinkedList.get(i).getId();
		    parentId = childrenLinkedList.get(i).getParent().getId();
		    for (int j = 0; j < parentIds.size(); j++) {
			if (parentIds.get(j) == parentId.intValue()) {
			    add = false;
			    break;
			}
		    }
		    if (add) {
			parentIds.add(parentId);
			treeIds.add(treeId);
		    }
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append("WRONG NO OF CHILDREN ERROR: LINKED LIST RANK ERROR DETECTED!");
		buffer.append("\nCheck nodes with Parent Id");
		for (int i = 0; i < parentIds.size(); i++) {
		    buffer.append(" : " + parentIds.get(i));
		}
		if (parentIds.size() > 1) {
		    buffer.append("\nAlso Check nodes with Id");
		    for (int i = 0; i < treeIds.size(); i++) {
			buffer.append(" : " + treeIds.get(i));
		    }
		}
		throw new PersistentException(buffer.toString());
	    }
	}
	while (childrenLinkedList.size() > 0) {
	    TestDesignTreeRefined refNode = TestDesignTreeRefined
		    .getDesignTree(childrenLinkedList.removeFirst());
	    constructDesignTree(refNode, thisNode);
	}
	return thisNode;
    }

    private TestDesignTreeNode getTestDesignTreeData(boolean showOutput,
	    String name) {
	T_test_designtree rootDesignTree = null;
	TestDesignTreeNode root = null;
	T_test_stepcontainer suiteObject = m_testSuites.get(name);
	if (suiteObject != null) {
	    try {
		try {
		    T_test_designtreeCriteria t_test_designtreeCriteria = new T_test_designtreeCriteria();
		    t_test_designtreeCriteria.elementId.eq(suiteObject.getId());
		    int partTypeId = getDesignPartTypeIdByName("TestSuite");
		    t_test_designtreeCriteria.typeId.eq(partTypeId);
		    T_test_designtree[] suiteTrees = t_test_designtreeCriteria
			    .listT_test_designtree();
		    if (suiteTrees != null && suiteTrees.length > 0) {
			if (suiteTrees.length == 1) {
			    rootDesignTree = suiteTrees[0];
			} else {
			    System.err
				    .println("SUITE DUPLICATE ERROR! Multiple DesignTrees are using this the same Test Suite entry! Check the T_test_designtrees with id");
			    for (int i = 0; i < suiteTrees.length; i++) {
				System.err.println(" : "
					+ suiteTrees[i].getId());
			    }
			    throw new PersistentException();
			}
		    } else {
			System.err
				.println("SUITE NOT ATTACHED ERROR! No design tree has been assigned to this Test Suite entry! Check the T_test_stepcontainer with id: "
					+ suiteObject.getId());
			throw new PersistentException();
		    }
		    if (rootDesignTree != null) {
			root = constructDesignTree(
				TestDesignTreeRefined
					.getDesignTree(rootDesignTree),
				null);
			if (showOutput) {
			    showtree(root, "");
			}
		    }
		} catch (PersistentException ex) {
		    ex.printStackTrace();
		} finally {
		    TestisDbPersistentManager.instance()
			    .disposePersistentManager();
		}
		return root;
	    } catch (PersistentException ex) {
		ex.printStackTrace();
	    }
	}
	return null;
    }

    public void showtree(TestDesignTreeNode node, String start) {
	// System.out.println(start + "Reference:" + node.getId() +
	// " Object:" + node.getObject());
	TestDesignTreeNode[] children = node.getChildren();
	if (children != null) {
	    for (int i = 0; i < children.length; i++) {
		showtree(children[i], start + "\t");
	    }
	}
    }

    public String[] getLabelNames() {
	LabelDataHandler handler = new LabelDataHandler();
	LinkedList<String> nameList = handler.getLabelNames();
	String[] result = new String[nameList.size()];
	nameList.toArray(result);
	return result;
    }

    public static T_test_label getLabelByName(String name) {
	LabelDataHandler handler = new LabelDataHandler();
	return handler.getLabelByName(name);
    }

    public static void saveLabels(LinkedList<String> labels,
	    T_test_stepcontainer temp1) throws PersistentException {
	T_test_labelpairs[] existingPairs;
	LabelDataHandler handler = new LabelDataHandler();
	if (temp1.t_test_labelpairs != null) {
	    existingPairs = temp1.t_test_labelpairs.toArray();
	} else {
	    existingPairs = new T_test_labelpairs[0];
	}
	for (int i = 0; i < existingPairs.length; i++) {
	    T_test_label existingLabel = handler.getLabelById(existingPairs[i]
		    .getLabelId());
	    ;
	    if (labels.contains(existingLabel.getName())) {
		labels.remove(existingLabel.getName());
	    } else {
		existingPairs[i].deleteAndDissociate();
	    }
	}
	for (int i = 0; i < labels.size(); i++) {
	    T_test_labelpairs pair = new T_test_labelpairs();
	    pair.setTestCase(temp1);
	    pair.setLabelId(getLabelByName(labels.get(i)).getId());
	    pair.save();
	}
    }

    public static void saveLabels(LinkedList<String> labels,
	    T_test_teststeps testStep) throws PersistentException {
	T_test_labelpairs[] existingPairs;
	LabelDataHandler handler = new LabelDataHandler();
	if (testStep.t_test_labelpairs != null) {
	    existingPairs = testStep.t_test_labelpairs.toArray();
	} else {
	    existingPairs = new T_test_labelpairs[0];
	}
	for (int i = 0; i < existingPairs.length; i++) {
	    T_test_label existingLabel = handler.getLabelById(existingPairs[i]
		    .getLabelId());
	    ;
	    if (labels.contains(existingLabel.getName())) {
		labels.remove(existingLabel.getName());
	    } else {
		existingPairs[i].deleteAndDissociate();
	    }
	}
	for (int i = 0; i < labels.size(); i++) {
	    T_test_labelpairs pair = new T_test_labelpairs();
	    pair.setTestStep(testStep);
	    pair.setLabelId(getLabelByName(labels.get(i)).getId());
	    pair.save();
	}
    }

    public static void saveLabels(LinkedList<String> labels,
	    T_test_dataobject dataobject) throws PersistentException {
	T_test_labelpairs[] existingPairs;
	LabelDataHandler handler = new LabelDataHandler();

	if (dataobject.t_test_labelpairs != null) {
	    existingPairs = dataobject.t_test_labelpairs.toArray();
	} else {
	    existingPairs = new T_test_labelpairs[0];
	}
	for (int i = 0; i < existingPairs.length; i++) {
	    T_test_label existingLabel = handler.getLabelById(existingPairs[i]
		    .getLabelId());
	    if (labels.contains(existingLabel.getName())) {
		labels.remove(existingLabel.getName());
	    } else {
		existingPairs[i].deleteAndDissociate();
	    }
	}
	for (int i = 0; i < labels.size(); i++) {
	    T_test_labelpairs pair = new T_test_labelpairs();
	    pair.setDataObject(dataobject);
	    pair.setLabelId(getLabelByName(labels.get(i)).getId());
	    pair.save();
	}
    }

    public static int setRankOfAdd(TestDesignTreeNode parentNode,
	    T_test_designtree newNode, int childIndex)
	    throws PersistentException {
	if (parentNode == null) {
	    return -1;
	}
	TestDesignTreeNode[] children = parentNode.getChildren();
	int childCount = children.length;
	if (childIndex < 0) {
	    childIndex = 0;
	}
	if (childCount > 0) {
	    String partTypeName = getDesignPartTypeName(newNode.getTypeId());
	    DesignPart firstChild = children[0].getObject();
	    DesignPart lastChild = children[children.length - 1].getObject();
	    if ((firstChild instanceof PreConditionCaseRefined)
		    && childIndex == 0) {
		childIndex++;
	    }
	    if ((lastChild instanceof PostConditionCaseRefined)
		    && childIndex == childCount) {
		childIndex--;
	    }
	    if (partTypeName.equals("PreConditionCase")) {
		childIndex = 0;
	    } else if (partTypeName.equals("PostConditionCase")) {
		childIndex = childCount;
	    }
	    if (childIndex == 0) {
		newNode.setRank(null);
		children[0].getReference().getTreeReference()
			.setRank(newNode.getId());
		children[0].getReference().getTreeReference().save();
	    } else if (childIndex < childCount) {
		newNode.setRank(children[childIndex - 1].getId());
		children[childIndex].getReference().getTreeReference()
			.setRank(newNode.getId());
		children[childIndex].getReference().getTreeReference().save();

	    } else {
		newNode.setRank(children[childCount - 1].getId());
	    }
	} else {
	    return -1;
	}
	return childIndex;
    }

    public TestDesignTreeNode operationPasteClone(
	    TestDesignTreeNode cloneObject, TestDesignTreeNode parentTreeNode,
	    int childIndex) throws PersistentException {
	AtofOrmTimer timer = new AtofOrmTimer();
	timer.reset();
	// System.out.println("___ CLONE ___" + " Source: " +
	// cloneObject.getName() + " Target: " + parentTreeNode.getName());

	int place = -1;
	TestDesignTreeNode newCloneNode = cloneObject
		.createRefinedDatabaseClone(parentTreeNode.getReference(), null);
	if (newCloneNode == null) {
	    return null;
	}
	place = setRankOfAdd(parentTreeNode, newCloneNode.getReference()
		.getTreeReference(), childIndex);
	if (place == -1) {
	    parentTreeNode.addChild(newCloneNode);
	} else {
	    parentTreeNode.addChild(place, newCloneNode);

	    newCloneNode.setPlace(place);
	}
	T_test_designtree newClone = newCloneNode.getReference()
		.getTreeReference();
	TestDesignTreeRefined newCloneRef = TestDesignTreeRefined
		.getDesignTree(newClone);
	newClone.setParent(parentTreeNode.getReference().getTreeReference());
	newClone.setClone(cloneObject.getReference().getOriginalTreeReference());
	newClone.setTypeId(newClone.getClone().getTypeId());
	newClone.setElementId(null);
	newClone.save();
	// timer.print(" operationPasteClone  in ms:");
	newCloneNode = TestDesignTreeNode.getNode(newCloneRef,
		cloneObject.getObject());
	return newCloneNode;

    }

    public TestDesignTreeNode operationPasteCopy(TestDesignTreeNode copyObject,
	    TestDesignTreeNode parentNode, int childIndex)
	    throws PersistentException {
	// System.out.println("___ COPY ___" + " Source: " +
	// copyObject.getName() + " Target: " + parentNode.getName());
	AtofOrmTimer timer = new AtofOrmTimer();
	timer.reset();
	TestDesignTreeNode newCopy = null;

	int place = -1;
	newCopy = copyObject.createRefinedDatabaseCopy(
		parentNode.getReference(), null);
	if (newCopy == null) {
	    return null;
	}
	place = setRankOfAdd(parentNode, newCopy.getReference()
		.getTreeReference(), childIndex);
	if (place == -1) {
	    parentNode.addChild(newCopy);
	} else {
	    parentNode.addChild(place, newCopy);
	    newCopy.setPlace(place);
	}
	// timer.print(" operationPasteCopy  in ms:");
	return newCopy;
    }

    public boolean checkIfAbstractParametersAreValid(String abstractParameter,
	    DynamicMapDesignTreeNode rootNode) {
	if (rootNode.searchObject("AbstractId", abstractParameter) == null) {
	    System.out.println("RootNode:" + rootNode.getName()
		    + " param not exists:" + abstractParameter);
	    return true;
	}
	return true;
    }

    public void removeTestSuite(String suiteName) {
	m_testSuites.remove(suiteName);
    }

    public boolean isValidDataObjectToSave(HashMap<String, Object> parameters,
	    TestDesignTreeNode thisNode) {
	boolean isValid = true;
	ParameterTable parameterTableModel = (ParameterTable) parameters
		.get("parameterTableModel");
	ParameterModel[] params = parameterTableModel.getAllItems();
	DataObjectRefined dataObject = (DataObjectRefined) thisNode.getObject();
	DynamicMapDesignTreeNode rootNode = null;
	try {
	    rootNode = DynamicMap.newInstance().getDynamicMapDesignTreeFomDB(
		    false, thisNode.getActiveDut().getId());
	} catch (PersistentException ex) {
	    System.out.println("Exception occured when getting dynamic map -> "
		    + ex.getMessage());
	}
	if (rootNode == null) {
	    return false;
	}
	for (int i = 0; i < params.length; i++) {
	    int moduleId = dataObject.getReference().getModulTypeId();
	    String moduleName = getModuleTypeName(moduleId);
	    if (moduleName.equals("WebAutomationModule")) {
		TestDesignTreeNode parentNode = ((TestDesignTreeNode) thisNode
			.getParent());
		int actionId = ((TestStepRefined) parentNode.getObject())
			.getReference().getActionId();
		String actionName = getActionTypeName(actionId);
		if (!actionName.equals("HandleDutIp")
			&& !actionName.equals("DefaultValueVerification")
			&& !actionName.equals("LanguageSelection")
			&& !actionName.equals("PageContentVerification")) {
		    Integer deviceId = parentNode.getReference()
			    .getParameterIntValue(
				    TestDesignTreeParameters.DeviceId.name());
		    if (deviceId != null) {
			isValid = isValid
				& checkIfAbstractParametersAreValid(
					params[i].getParameter(), rootNode);
			if (!isValid) {
			    break;
			}
		    } else {
			TestDesignTreeNode tempParentNode = parentNode;
			while (!(tempParentNode.getObject() instanceof TestPlanRefined)) {
			    tempParentNode = (TestDesignTreeNode) tempParentNode
				    .getParent();
			}
			isValid = isValid
				& checkIfAbstractParametersAreValid(
					params[i].getParameter(), rootNode);
			if (!isValid) {
			    break;
			}
		    }
		}
	    }
	}
	return isValid;
    }

    public boolean isValidDataObjectToAdd(HashMap<String, Object> parameters,
	    TestDesignTreeNode parentNode) {
	boolean isValid = true;
	ParameterTable parameterTableModel = (ParameterTable) parameters
		.get("parameterTableModel");
	ParameterModel[] params = parameterTableModel.getAllItems();
	DynamicMapDesignTreeNode rootNode = null;
	try {
	    rootNode = DynamicMap.newInstance().getDynamicMapDesignTreeFomDB(
		    false, parentNode.getActiveDut().getId());
	} catch (PersistentException ex) {
	    System.out.println("Exception occured when getting dynamic map -> "
		    + ex.getMessage());
	}
	if (rootNode == null) {
	    return false;
	}
	String modulType = (String) parameters.get("modulType");
	for (int i = 0; i < params.length; i++) {
	    if (modulType.equals("WebAutomationModule")) {
		int actionId = ((TestStepRefined) parentNode.getObject())
			.getReference().getActionId();
		String actionName = getActionTypeName(actionId);
		if (!actionName.equals("HandleDutIp")
			&& !actionName.equals("DefaultValueVerification")
			&& !actionName.equals("LanguageSelection")
			&& !actionName.equals("PageContentVerification")) {
		    Integer deviceId = parentNode.getReference()
			    .getParameterIntValue(
				    TestDesignTreeParameters.DeviceId.name());
		    if (deviceId != null) {
			isValid = isValid
				& checkIfAbstractParametersAreValid(
					params[i].getParameter(), rootNode);
			if (!isValid) {
			    break;
			}
		    } else {
			TestDesignTreeNode tempParentNode = parentNode;
			while (!(tempParentNode.getObject() instanceof TestPlanRefined)) {
			    tempParentNode = (TestDesignTreeNode) tempParentNode
				    .getParent();
			}
			isValid = isValid
				& checkIfAbstractParametersAreValid(
					params[i].getParameter(), rootNode);
			if (!isValid) {
			    break;
			}
		    }
		}
	    }
	}
	return isValid;
    }

    private T_test_stepcontainer[] getTestSuites() {
	T_test_stepcontainer[] suiteList = null;
	if (m_testSuites.size() == 0) {
	    T_test_stepcontainerCriteria containerCriteria;
	    try {
		containerCriteria = new T_test_stepcontainerCriteria();
		containerCriteria.containerTypeId.eq(TestDesign
			.getDesignPartTypeIdByName("TestSuite"));
		suiteList = containerCriteria.listT_test_stepcontainer();
		for (int i = 0; i < suiteList.length; i++) {
		    m_testSuites.put(suiteList[i].getName(), suiteList[i]);
		}
	    } catch (PersistentException ex) {
		ex.printStackTrace();
	    }

	} else {
	    suiteList = m_testSuites.values().toArray(
		    new T_test_stepcontainer[m_testSuites.size()]);
	}
	return suiteList;
    }

    public String[] getTestSuiteNames() {
	String[] result = null;
	T_test_stepcontainer[] suiteList = getTestSuites();
	if (suiteList != null && suiteList.length > 0) {
	    result = new String[suiteList.length];
	    for (int i = 0; i < suiteList.length; i++) {
		result[i] = suiteList[i].getName();
		suiteList[i] = null;
	    }
	}
	return result;
    }

    public String getTestSuiteDetails(String name) {
	T_test_stepcontainer suite = m_testSuites.get(name);
	if (suite != null) {
	    String result = "Id:" + suite.getId();
	    result += "\nName:" + suite.getName();
	    result += "\nDescription:" + suite.getDescription();
	    return result;
	} else {
	    return "Suite not found!";
	}
    }

    public boolean convertCloneOfGhostToOriginal(T_test_designtree clone,
	    T_test_designtree ghost) {
	try {
	    PersistentTransaction t = TestisDbPersistentManager.instance()
		    .getSession().beginTransaction();
	    try {
		T_test_designtree[] children = clone.t_test_designtree
			.toArray();
		for (int i = 0; i < children.length; i++) {
		    children[i].setParent(ghost);
		    children[i].save();
		}
		children = clone.getParent().t_test_designtree.toArray();
		for (int i = 0; i < children.length; i++) {
		    if (children[i].getRank() != null
			    && children[i].getRank().intValue() == clone
				    .getId()) {
			children[i].setRank(ghost.getId());
			children[i].save();
			break;
		    }
		}
		TestDesignTreeRefined ghostNode = TestDesignTreeRefined
			.getDesignTree(ghost);
		TestDesignTreeRefined cloneNode = TestDesignTreeRefined
			.getDesignTree(clone);
		TestDesignTreeRefined cloneNodeParent = TestDesignTreeRefined
			.getDesignTree(clone.getParent());
		String browserType = cloneNode
			.getParameterStringValue(TestDesignTreeParameters.BrowserType
				.name());
		Integer browserSpeed = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.BrowserSpeed
				.name());
		String deviceIp = cloneNode
			.getParameterStringValue(TestDesignTreeParameters.DeviceIp
				.name());

		Integer deviceId = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.DeviceId
				.name());
		Integer nicId = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.NicId
				.name());
		Integer pcId = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.PcId
				.name());
		Integer languageId = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.LanguageId
				.name());
		Integer profileId = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.ProfileId
				.name());
		Integer testBedId = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.TestBedId
				.name());
		Integer ownerId = cloneNode
			.getParameterIntValue(TestDesignTreeParameters.OwnerId
				.name());

		ghostNode.setParameterValue(
			TestDesignTreeParameters.PcId.name(), pcId);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.DeviceId.name(), deviceId);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.NicId.name(), nicId);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.DeviceIp.name(), deviceIp);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.BrowserSpeed.name(),
			browserSpeed);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.BrowserType.name(),
			browserType);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.LanguageId.name(), languageId);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.ProfileId.name(), profileId);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.TestBedId.name(), testBedId);
		ghostNode.setParameterValue(
			TestDesignTreeParameters.OwnerId.name(), ownerId);

		ghost.setParent(clone.getParent());
		ghost.setRank(clone.getRank());
		ghost.setTypeId(clone.getTypeId());
		ghost.save();
		TestDesignTreeNode.getNode(cloneNodeParent).deleteChild(
			TestDesignTreeNode.getNode(cloneNode));
		clone.deleteAndDissociate();
		t.commit();
		return true;
	    } catch (PersistentException ex) {
		t.rollback();
		ex.printStackTrace();
	    }
	} catch (PersistentException ex) {
	    ex.printStackTrace();
	}
	return false;
    }

    public boolean handleMoveObjectRanks(
	    TestDesignTreeNode currentPrevDesignTreeNode,
	    TestDesignTreeNode currentNextDesignTreeNode,
	    TestDesignTreeNode newPrevTreeNode,
	    TestDesignTreeNode newNextTreeNode,
	    TestDesignTreeNode currentDesignTreeNode) {
	try {
	    PersistentTransaction t = TestisDbPersistentManager.instance()
		    .getSession().beginTransaction();
	    try {
		boolean result = true;
		boolean newResult;
		if (currentNextDesignTreeNode != null) {
		    if (currentPrevDesignTreeNode != null) {
			currentNextDesignTreeNode
				.getReference()
				.getTreeReference()
				.setRank(
					currentPrevDesignTreeNode
						.getReference()
						.getTreeReference().getId());
		    } else {
			currentNextDesignTreeNode.getReference()
				.getTreeReference().setRank(null);
		    }
		    newResult = currentNextDesignTreeNode.getReference()
			    .getTreeReference().save();
		    result = result && newResult;
		}
		if (newNextTreeNode != null) {
		    Integer newPrevSibling = newNextTreeNode.getReference()
			    .getTreeReference().getRank();

		    currentDesignTreeNode.getReference().getTreeReference()
			    .setRank(newPrevSibling);
		    newResult = currentDesignTreeNode.getReference()
			    .getTreeReference().save();
		    result = result && newResult;

		    newNextTreeNode
			    .getReference()
			    .getTreeReference()
			    .setRank(
				    currentDesignTreeNode.getReference()
					    .getTreeReference().getId());
		    newResult = newNextTreeNode.getReference()
			    .getTreeReference().save();
		    result = result && newResult;

		} else {
		    Integer newRank = null;
		    if (newPrevTreeNode != null) {
			newRank = newPrevTreeNode.getId();
		    }
		    currentDesignTreeNode.getReference().getTreeReference()
			    .setRank(newRank);
		    newResult = currentDesignTreeNode.getReference()
			    .getTreeReference().save();
		    result = result && newResult;
		}
		if (result) {
		    t.commit();
		    return result;
		} else {
		    throw new PersistentException();
		}
	    } catch (PersistentException e) {
		t.rollback();
		e.printStackTrace();
	    } finally {
		TestisDbPersistentManager.instance().disposePersistentManager();
	    }
	} catch (PersistentException e) {
	    e.printStackTrace();
	}
	return false;
    }

    public void fixChildren(TestDesignTreeNode parent) {
	if (parent == null) {
	    return;
	} else if (parent.getReference().getTreeReference() == null) {
	    return;
	} else if (parent.getReference().getTreeReference().t_test_designtree == null) {
	    return;
	}
	T_test_designtree[] children = parent.getReference().getTreeReference().t_test_designtree
		.toArray();
	HashMap<Integer, T_test_designtree> sortedChildList = new HashMap<Integer, T_test_designtree>();
	for (int i = 0; i < children.length; i++) {
	    if (children[i].getRank() == null) {
		sortedChildList.put(0, children[i]);
	    } else {
		sortedChildList.put(children[i].getRank(), children[i]);
	    }
	}
	T_test_designtree temp;
	int nextChild = 0;
	while (sortedChildList.containsKey(nextChild)) {
	    temp = sortedChildList.get(nextChild);
	    TestDesignTreeRefined tempNode = TestDesignTreeRefined
		    .getDesignTree(temp);
	    nextChild = temp.getId();
	    parent.addChild(TestDesignTreeNode.getNode(tempNode));
	}
    }
}
